package com.gushenge.core.base.activity

import android.content.res.Configuration
import android.content.res.Resources
import android.os.Bundle
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.BarUtils
import com.gushenge.atools.util.AView
import com.gushenge.core.base.viewmodel.BaseViewModel
import com.gushenge.core.getVmClazz
import com.shuyu.gsyvideoplayer.GSYVideoManager
import me.jessyan.autosize.AutoSizeCompat

/**增加下loadsir
 */
abstract class BaseVmActivity<VM : BaseViewModel>(val  layoutid:Int) : AppCompatActivity() {

    /**
     * 是否需要使用DataBinding 供子类BaseVmDbActivity修改，用户请慎动
     */
    private var isUserDb = false

    lateinit var mViewModel: VM


    abstract fun initView(savedInstanceState: Bundle?)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        BarUtils. transparentStatusBar(this)
        if (!isUserDb) {
            setContentView(layoutid)
        } else {
            initDataBind()
        }
        AView.setStatusBar(this@BaseVmActivity,true)
        init(savedInstanceState)
    }

    private fun init(savedInstanceState: Bundle?) {
        mViewModel = createViewModel()
        initView(savedInstanceState)
    }


    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVmClazz(this))
    }


    fun userDataBinding(isUserDb: Boolean) {
        this.isUserDb = isUserDb
    }

    /**
     * 供子类BaseVmDbActivity 初始化Databinding操作
     */
    open fun initDataBind() {}

    override fun onDestroy() {
        GSYVideoManager.releaseAllVideos()
        super.onDestroy()
    }

    override fun getResources(): Resources {
        val resources = super.getResources()
        try {
            val configuration = Configuration()
            configuration.setToDefaults()
            resources?.updateConfiguration(configuration, resources.displayMetrics)
            AutoSizeCompat.autoConvertDensityOfGlobal(resources)
            if (Looper.myLooper() == Looper.getMainLooper()) {
                AutoSizeCompat.autoConvertDensity(
                    resources,
                    375.toFloat(),
                    resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
                )
            }
        } catch (e: Exception) {
        } finally {
            return resources
        }
        return resources

    }
}